#include <header.h>
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	char *port = "8080";
	char *ip = "192.168.169.128";
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in clientaddr;
	clientaddr.sin_family = AF_INET;
	clientaddr.sin_port = htons(atoi(port));
	clientaddr.sin_addr.s_addr = inet_addr(ip);

	int ret = connect(socket_fd, (struct sockaddr*)&clientaddr, sizeof clientaddr);
	ERROR_CHECK(ret, -1, "connect");

	fd_set set;
	FD_ZERO(&set);

	while(1){
		FD_SET(STDIN_FILENO, &set);
		FD_SET(socket_fd, &set);

		int res = select(10, &set, NULL, NULL, NULL);
		ERROR_CHECK(res, -1, "select");
		
		char buf[1 << 10] = {0};
		if(FD_ISSET(STDIN_FILENO, &set)){
			// TODO read stdin
			__bzero(buf, sizeof buf);			
			ssize_t ret = read(STDIN_FILENO, buf, sizeof buf);
			ERROR_CHECK(ret, -1, "read from stdin");

			int ret1 = send(socket_fd, buf, sizeof buf, 0);
			ERROR_CHECK(ret1, -1, "send");

		}
		if(FD_ISSET(socket_fd, &set)){
			// read from socket
			__bzero(buf, sizeof buf);
			ssize_t byte = recv(socket_fd, buf, sizeof buf, 0);
			if(byte == 0){
				printf("对方已断开\n");
				break;
			}
			printf("server:%s\n", buf);	
		}
	}

	close(socket_fd);
	return 0;
}